package com.tkmybatis.hfy.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.web.multipart.MultipartFile;  
/** 
 * excel读写工具类 */  
@Slf4j
public class PoiUtils {  
    private final static String xls = "xls";  
    private final static String xlsx = "xlsx";  
    
    public static List<String[]> readExcel(MultipartFile file) throws IOException{  
        //检查文件  
        checkFile(file);  
        //获得Workbook工作薄对象  
        Workbook workbook = getWorkBook(file);  
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回  
        List<String[]> list = new ArrayList<String[]>();  
        if(workbook != null){
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
                //获得当前sheet工作表  
                Sheet sheet = workbook.getSheetAt(sheetNum);  
                if(sheet == null){  
                    continue;  
                }  
                Map<String, PictureData> maplist = new HashMap<String, PictureData>();
                String fileName = file.getOriginalFilename();  
                if(fileName != null && fileName.endsWith(xls)){  
                	maplist = getPictures1((HSSFSheet) sheet);
                }else if(fileName != null && fileName.endsWith(xlsx)){ 
                	maplist = getPictures2((XSSFSheet) sheet);
                }
                //获得当前sheet的开始行  
                int firstRowNum  = sheet.getFirstRowNum();  
                //获得当前sheet的结束行  
                int lastRowNum = sheet.getLastRowNum();  
                //循环除了第一行的所有行  
                for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){  
                    //获得当前行  
                    Row row = sheet.getRow(rowNum);  
                    if(row == null || row.getPhysicalNumberOfCells()==0){
                    	list.add(null);
                        continue;  
                    }  
                    //获得当前行的开始列  
                    int firstCellNum = row.getFirstCellNum();  
                    //获得当前行的列数  
                    int lastCellNum = row.getPhysicalNumberOfCells();  
                    String[] cells = new String[lastCellNum];  
                    //循环当前行  
                    for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
                        Cell cell = row.getCell(cellNum);  
                        cells[cellNum] = getCellValue(cell);  
                    }
                    list.add(cells);  
                }  
            }  
        }
        return list;  
    }
    
    
    public static List<Object[]> readExcelFile(MultipartFile file) throws IOException{  
        //检查文件  
        checkFile(file);  
        //获得Workbook工作薄对象  
        Workbook workbook = getWorkBook(file);  
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回  
        List<Object[]> list = new ArrayList<Object[]>();  
        if(workbook != null){
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
                //获得当前sheet工作表  
                Sheet sheet = workbook.getSheetAt(sheetNum);  
                if(sheet == null){  
                    continue;  
                }  
                //获得当前sheet的开始行  
                int firstRowNum  = sheet.getFirstRowNum();  
                //获得当前sheet的结束行  
                int lastRowNum = sheet.getLastRowNum();  
                //循环除了第一行的所有行  
                for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){  
                    //获得当前行  
                    Row row = sheet.getRow(rowNum);  
                    if(row == null || row.getPhysicalNumberOfCells()==0){
                    	list.add(null);
                        continue;  
                    }  
                    //获得当前行的开始列  
                    int firstCellNum = row.getFirstCellNum();  
                    //获得当前行的列数  
                    int lastCellNum = row.getPhysicalNumberOfCells();  
                    String[] cells = new String[lastCellNum];  
                    //循环当前行  
                    for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
                        Cell cell = row.getCell(cellNum);  
                        cells[cellNum] = getCellValue(cell);  
                    }
                    list.add(cells);  
                }  
            }  
        }
        return list;  
    }
    
    /**
	 * 
	 * 获取图片和位置 (xls)
	 * 
	 * @param sheet
	 * 
	 * @return
	 * 
	 * @throws IOException
	 * 
	 */
	public static Map<String, PictureData> getPictures1(HSSFSheet sheet) throws IOException {
		Map<String, PictureData> map = new HashMap<String, PictureData>();
		HSSFPatriarch drawingPatriarch = sheet.getDrawingPatriarch();
		if(drawingPatriarch != null) {
			List<HSSFShape> list = drawingPatriarch.getChildren();
			for (HSSFShape shape : list) {
				if (shape instanceof HSSFPicture) {
					HSSFPicture picture = (HSSFPicture) shape;
					HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
					PictureData pdata = picture.getPictureData();
					String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
					map.put(key, pdata);
				}
			}
		}
		return map;
	}

	/**
	 * 
	 * 获取图片和位置 (xlsx)
	 * 
	 * @param sheet
	 * 
	 * @return
	 * 
	 * @throws IOException
	 * 
	 */
	public static Map<String, PictureData> getPictures2(XSSFSheet sheet) throws IOException {
		Map<String, PictureData> map = new HashMap<String, PictureData>();
		List<POIXMLDocumentPart> list = sheet.getRelations();
		for (POIXMLDocumentPart part : list) {
			if (part instanceof XSSFDrawing) {
				XSSFDrawing drawing = (XSSFDrawing) part;
				List<XSSFShape> shapes = drawing.getShapes();
				for (XSSFShape shape : shapes) {
					XSSFPicture picture = (XSSFPicture) shape;
					XSSFClientAnchor anchor = picture.getPreferredSize();
					CTMarker marker = anchor.getFrom();
					String key = marker.getRow() + "-" + marker.getCol();
					map.put(key, picture.getPictureData());
				}
			}
		}
		return map;

	}
    
    public static void checkFile(MultipartFile file) throws IOException{  
        //判断文件是否存在  
        if(null == file){  
            log.error("文件不存在！");  
            throw new FileNotFoundException("文件不存在！");  
        }  
        //获得文件名  
        String fileName = file.getOriginalFilename();  
        //判断文件是否是excel文件  
        if(fileName != null && !fileName.endsWith(xls) && !fileName.endsWith(xlsx)){  
            log.error(fileName + "不是excel文件");  
            throw new IOException(fileName + "不是excel文件");  
        }  
    }  
    public static Workbook getWorkBook(MultipartFile file) {  
        //获得文件名  
        String fileName = file.getOriginalFilename();  
        //创建Workbook工作薄对象，表示整个excel  
        InputStream is = null;
        try {  
            //获取excel文件的io流  
            is = file.getInputStream();  
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象  
            if(fileName != null && fileName.endsWith(xls)){  
                //2003  
            	Workbook workbook = new HSSFWorkbook(is);  
            	 return workbook; 
            }else if(fileName != null && fileName.endsWith(xlsx)){  
                //2007  
//            	File f = new File("C:\\Users\\Administrator.DESKTOP-9L2D1UM\\Desktop\\111.xlsx");
//            	file.transferTo(f);
//            	XSSFWorkbook workbook = new XSSFWorkbook(f.getPath());
            	XSSFWorkbook workbook = new XSSFWorkbook(is);
            	 return workbook; 
            }  
        } catch (IOException e) {  
        	log.error("error:",e);
            log.info(e.getMessage());  
            try {
            	if(is != null) {
            		is.close();
            	}
			} catch (IOException e2) {
				log.error("error:",e);
			}
        } finally{
        	try {
        		if(is != null) {
            		is.close();
            	}
			} catch (IOException e) {
				log.error("error:",e);
			}
        }
        return null;
    }  
    @SuppressWarnings("deprecation")
	public static String getCellValue(Cell cell){  
        String cellValue = "";  
        if(cell == null){  
            return cellValue;  
        }  
        //把数字当成String来读，避免出现1读成1.0的情况  
        if(cell.getCellTypeEnum() == CellType.STRING){  
            cell.setCellType(CellType.STRING);  
        }  
        //判断数据的类型  
        switch (cell.getCellTypeEnum()){  
            case NUMERIC: //数字  
                cellValue = String.valueOf(cell.getNumericCellValue());  
                break;  
            case STRING: //字符串  
                cellValue = String.valueOf(cell.getStringCellValue());  
                break;  
            case BOOLEAN: //Boolean  
                cellValue = String.valueOf(cell.getBooleanCellValue());  
                break;  
            case FORMULA: //公式  
                cellValue = String.valueOf(cell.getCellFormula());  
                break;  
            case BLANK: //空值   
                cellValue = "";  
                break;  
            case ERROR: //故障  
                cellValue = "非法字符";  
                break;  
            default:  
                cellValue = "未知类型";  
                break;  
        }  
        return cellValue;  
    }  
    
    public static List<String[]> readGxtlsExcel(MultipartFile file) throws IOException{  
        //检查文件  
        checkFile(file);  
        //获得Workbook工作薄对象  
        Workbook workbook = getWorkBook(file);  
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回  
        List<String[]> list = new ArrayList<String[]>();  
        if(workbook != null){
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
                //获得当前sheet工作表  
                Sheet sheet = workbook.getSheetAt(sheetNum);  
                if(sheet == null){  
                    continue;  
                }  
                Map<String, PictureData> maplist = new HashMap<String, PictureData>();
                String fileName = file.getOriginalFilename();  
                if(fileName != null && fileName.endsWith(xls)){  
                	maplist = getPictures1((HSSFSheet) sheet);
                }else if(fileName != null && fileName.endsWith(xlsx)){ 
                	maplist = getPictures2((XSSFSheet) sheet);
                }
                //获得当前sheet的开始行  
                int firstRowNum  = sheet.getFirstRowNum();  
                //获得当前sheet的结束行  
                int lastRowNum = sheet.getLastRowNum();  
                //循环除了第一行的所有行  
                for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){  
                    //获得当前行  
                    Row row = sheet.getRow(rowNum);  
                    if(row == null || row.getPhysicalNumberOfCells()==0){
                    	list.add(null);
                        continue;  
                    }  
                    //获得当前行的开始列  
                    int firstCellNum = row.getFirstCellNum();  
                    //获得当前行的列数  
                    //int lastCellNum = row.getPhysicalNumberOfCells();  
                    String[] cells = new String[sheet.getRow(2).getPhysicalNumberOfCells()];  
                    //循环当前行  
                    for(int cellNum = firstCellNum; cellNum < cells.length;cellNum++){  
                        Cell cell = row.getCell(cellNum);  
                        cells[cellNum] = getCellValue(cell);  
                    }
                    list.add(cells);  
                }  
            }  
        }
        return list;  
    }
}